package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private IPermissionService permissionService;

    //处理查询所有部门的请求
    @RequestMapping("/list")
    public String list(Model model,QueryObject qo){
        //查询所有部门数据,存在模型
        //List<Permission> permissions = permissionService.listAll();
        //处理分页查询部门的请求
        //model.addAttribute("permissions",permissions);
        PageInfo<Permission> pageInfo= permissionService.query(qo);
        model.addAttribute("pageResult",pageInfo);
        return "permission/list";  //  /WEB-INF/views/permission/list.ftl
    }

    //处理删除请求
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            if (id != null) {
                permissionService.delete(id);
            }
            return new JsonResult();
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }

    }

    //处理去新增请求
    @RequestMapping("/input")
    public String input(Long id,Model model){

        //如果传id就传去修改
        if (id!=null){
            model.addAttribute("permission",permissionService.get(id));
        }
        return "permission/input";
    }

    //处理新增请求
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Permission permission){
        if (permission.getId()!=null){
            //修改
            permissionService.update(permission);
        }else {
            //新增
            permissionService.save(permission);
        }
        return "redirect:/permission/list.do";
    }

    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        try {
            permissionService.reload();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"加载失败");
        }
    }
}
